package com.zucc.config;

import com.alibaba.fastjson.JSONObject;
import com.zucc.annotation.IgnoreResponseWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;

@RestControllerAdvice(basePackages = "com.zucc")
@Slf4j
public class RespAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        Method method = methodParameter.getMethod();
        return method.getAnnotation(ResponseBody.class) != null || method.getDeclaringClass().isAnnotationPresent(RestController.class);
    }

    @Override
    public Object beforeBodyWrite(Object obj, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        Method method = methodParameter.getMethod();
        // 带有IgnoreResponseWrapper注解的方法|返回类型是RailwayFacadeResponse 不执行返回值包装
        if (method.getAnnotation(IgnoreResponseWrapper.class) != null || obj instanceof Resp) {
            return obj;
        }
        Resp result = new Resp();
        result.setCode(0);
        result.setMsg("success");
        result.setData(obj);
        log.info("result = {}", JSONObject.toJSONString(result));
        return result;
    }

}
